package com.mbc.hr.manager;

import java.util.Date;
import java.util.List;

import com.mbc.common.exception.DataDuplicationException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.hr.entities.Holiday;

public class HolidayMgr extends AbstractMgr {
	
	public HolidayMgr(){}
		
	public HolidayMgr(String sessionId){
		this.sessionId = sessionId;
	}
	
	public void createHoliday(Holiday holiday)throws Exception{
		openConnection();
		try {
			beginTransaction();
			holiday.setHolidayID(KeyGenerator.generateKey(entityManager));
			entityManager.persist(holiday);
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			if(DataDuplicationException.isUniqueKyeError(e))
				throw new DataDuplicationException(e.getMessage());
			else
				throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void updateHoliday(Holiday holiday)throws Exception{
		openConnection();
		try {
			beginTransaction();
			entityManager.merge(holiday);
			commitTransaction();
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void deleteHoliday(long id)throws Exception{
		openConnection();
		try {
			beginTransaction();
			Holiday l_holiday = entityManager.find(Holiday.class, id);
			entityManager.remove(l_holiday);
			commitTransaction();
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public List<Holiday> getHolidays(Date startDate, Date endDate)throws Exception{
		openConnection();
		try {
			return entityManager.createNamedQuery("Holiday.findBetween", Holiday.class)
					.setParameter("startDate", startDate)
					.setParameter("endDate", endDate)
					.getResultList();
		} catch (Exception e) {
				throw e;
		} finally{
			closeConnection();
		}
	}
}
